<template>
  <ul id="example-1">
    <li v-for="(item, index) in list" :key="index">
      <p>id: {{ item.id}}</p>
      <p>{{item.orderUserName}}</p>
      <p v-if="timeTable[item.id]">倒计时: {{timeTable[item.id]}}</p>
      <p v-else>订单取消</p>
    </li>
  </ul>
</template>

<script>
import data from "./data";

export default {
  name: "app",
  data() {
    return {
      data: {},
      list: [],
      countTable: {},
      timeTable: {}
    };
  },
  created() {
    this.requst();
  },
  beforeDestroy() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  },
  methods: {
    requst() {
      setTimeout(() => {
        this.data = data.data;
        this.list = data.data.list;
        this.countDown();
      }, 2000);
    },
    cancelOrder(id) {
      alert(`订单${id} 被取消`);
    },
    countDown() {
      if (this.interval) {
        clearInterval(this.interval);
      }

      this.list.forEach(item => {
        const time =
          new Date(item.updateTime).getTime() + 1000 * 60 * 30 - Date.now();
        this.countTable[item.id] = time > 0 ? time : 0;
      });

      this.interval = setInterval(this.interval.bind(this), 1000);
    },
    interval() {
      const table = {};
      Object.keys(this.countTable).forEach(key => {
        const lastTime = this.countTable[key];
        if (lastTime) {
          const time = lastTime - 1000;
          this.countTable[key] = time < 0 ? 0 : time;
          if (!this.countTable[key]) {
            this.cancelOrder(key);
            table[key] = undefined;
          } else {
            table[key] = this.converTime(time);
          }
        } else {
          table[key] = undefined;
        }
      });
      console.log(table);
      this.timeTable = table;
    },
    converTime(time) {
      const sencond = Math.ceil(time / 1000);
      console.log(sencond / 3600, sencond / 60);
      const hour = Math.floor(sencond / 3600);
      const min = Math.floor((sencond % 3600) / 60);
      const ss = sencond - hour * 3600 - min * 60;
      return `${hour}:${min}:${ss}`;
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
